package com.lyh.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyh.common.constant.CacheConstants;
import com.lyh.common.constant.Constants;
import com.lyh.common.core.domain.AjaxResult;
import com.lyh.common.core.domain.entity.SysUser;
import com.lyh.common.core.domain.model.LoginBody;
import com.lyh.common.core.domain.model.LoginCodeBody;
import com.lyh.common.core.redis.RedisCache;
import com.lyh.common.exception.user.UserNotExistsException;
import com.lyh.common.utils.CommonUtils;
import com.lyh.common.utils.SMSUtils;
import com.lyh.common.utils.SecurityUtils;
import com.lyh.common.utils.uuid.IdUtils;
import com.lyh.framework.web.service.SysLoginService;
import com.lyh.framework.web.service.TokenService;
import com.lyh.system.domain.req.SysUserPasswordReq;
import com.lyh.system.domain.vo.UserInfoVo;
import com.lyh.system.mapper.SysUserMapper;
import com.lyh.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * 登录验证
 *
 * @author lyh
 */
@Api(value = "用户登录管理", description = "用户登录管理-在用")
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SMSUtils smsUtils;

    @Autowired
    private TokenService tokenService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("用户登录(验证码)web")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginCodeBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginByCode(loginBody.getTelephone(), loginBody.getCode());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    @ApiOperation("退出登录web")
    @PostMapping("/loginOut")
    public AjaxResult loginOut() {
        AjaxResult ajax = AjaxResult.success();
        // 互踢退出登录
        String userIdKey = tokenService.getUserIdKey(SecurityUtils.getLoginUser().getUserId());
        redisCache.deleteObject(userIdKey);
        return ajax;

    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("用户登录(密码)")
    @PostMapping("/pwdLogin")
    public AjaxResult pwdlogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        //判断账号是否是后台管理的权限
        List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, loginBody.getUsername()));
        if(sysUsers!=null && sysUsers.size()>0){
            Integer isAdmin = sysUsers.get(0).getIsAdmin();
            if(isAdmin == 0){
              return  AjaxResult.error("无后台管理权限");
            }
        }
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());

        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("获取当前用户信息")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysUser sysUser = sysUserMapper.selectById(user.getUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", sysUser);
        return ajax;
    }

    /**
     * app 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/app/getInfo")
    @ApiOperation("获取当前app用户信息")
    public AjaxResult appGetInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user == null) {
            throw new UserNotExistsException();
        }
        UserInfoVo userInfo = sysUserMapper.getUserInfo(user.getUserId());
        return AjaxResult.success(userInfo);
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("用户登录(密码)")
    @PostMapping("/appLogin")
    public AjaxResult appLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = new AjaxResult<>();
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", loginBody.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser == null || isBlank(sysUser.getMemberId()) || sysUser.getIsAdmin() != 0) {
            return AjaxResult.error("用户名或密码错误！");
        }
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return AjaxResult.success("登录成功！", ajax);
    }

    @ApiOperation("修改密码")
    @PostMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestBody @Validated SysUserPasswordReq req) {

        return AjaxResult.success(sysUserService.updatetPassword(req));
    }

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     * @throws Exception
     */
    @PostMapping("/appCaptcha")
    public AjaxResult getAppCode(@RequestParam String phone) throws Exception {
        AjaxResult ajax = new AjaxResult();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID(); //生成一个uuid
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        // 生成四位数验证码
        String code = CommonUtils.getRandomNum(4);
        // 通过阿里云短信发送短信
        String sendMessage = smsUtils.sendMessage(phone, code);
        //把验证码答应存入缓存，15分钟的时间
        redisCache.setCacheObject(verifyKey, code, Constants.CODE_EXPIRATION, TimeUnit.MINUTES);
        //把信息封装返回
        ajax.put("uuid", uuid);
        return AjaxResult.success("", ajax);
    }

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     * @throws Exception
     */
    @ApiOperation("验证码-修改密码")
    @GetMapping("/webSmsCode")
    public AjaxResult webCaptcha(@RequestParam String phone) throws Exception {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY_PSD + phone;
        // 生成四位数验证码
        String code = CommonUtils.getRandomNum(4);
        // 通过阿里云短信发送短信
        smsUtils.sendPsdMessage(phone, code);
        //把验证码答应存入缓存，15分钟的时间
        redisCache.setCacheObject(verifyKey, code, Constants.CODE_EXPIRATION, TimeUnit.MINUTES);
        return AjaxResult.success();
    }
}
